import os
import time
from datetime import datetime, timedelta


def find_recently_modified_folders(directory, days=3, include_subfolders=True):
    """
    找出指定目录下三天内更新过的文件夹

    参数:
    directory: 要检查的目录路径
    days: 检查的天数范围（默认3天）
    include_subfolders: 是否包含子文件夹（默认True）

    返回:
    最近修改的文件夹路径列表
    """
    # 计算时间阈值（当前时间减去指定的天数）
    time_threshold = time.time() - (days * 24 * 60 * 60)

    recently_modified = []

    try:
        if include_subfolders:
            # 使用os.walk递归遍历所有子文件夹
            for root, dirs, files in os.walk(directory):
                for dir_name in dirs:
                    folder_path = os.path.join(root, dir_name)
                    if is_folder_recently_modified(folder_path, time_threshold):
                        recently_modified.append(folder_path)
        else:
            # 只检查给定路径
            if os.path.isdir(directory) and is_folder_recently_modified(directory, time_threshold):
                recently_modified.append(directory)
            # 只检查指定目录的直接子文件夹
            # for item in os.listdir(directory):
            #     folder_path = os.path.join(directory, item)
            #     if os.path.isdir(folder_path) and is_folder_recently_modified(folder_path, time_threshold):
            #         recently_modified.append(folder_path)

    except PermissionError:
        print(f"权限不足，无法访问目录: {directory}")
    except FileNotFoundError:
        print(f"目录不存在: {directory}")
    except Exception as e:
        print(f"发生错误: {e}")

    return recently_modified


def is_folder_recently_modified(folder_path, time_threshold):
    """检查文件夹是否在指定时间阈值内被修改过"""
    try:
        # 获取文件夹的最后修改时间[5,6](@ref)
        modification_time = os.path.getmtime(folder_path)
        return modification_time > time_threshold
    except Exception:
        return False


def get_folder_modification_time(folder_path):
    """获取文件夹的可读修改时间"""
    try:
        mtime = os.path.getmtime(folder_path)
        return datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return "未知"


def main():
    # 设置要检查的目录路径
    target_directory = input("请输入要检查的目录路径（留空则使用当前目录）: ").strip()

    if not target_directory:
        target_directory = os.getcwd()

    if not os.path.exists(target_directory):
        print("指定的目录不存在！")
        return

    # 获取三天内修改过的文件夹
    recent_folders = find_recently_modified_folders(target_directory, days=3)

    if recent_folders:
        print(f"\n在 '{target_directory}' 中找到 {len(recent_folders)} 个最近3天内修改过的文件夹:\n")

        # 按修改时间排序（最新的排前面）
        recent_folders.sort(key=lambda x: os.path.getmtime(x), reverse=True)

        for i, folder in enumerate(recent_folders, 1):
            mod_time = get_folder_modification_time(folder)
            print(f"{i}. {folder}")
            print(f"   最后修改时间: {mod_time}\n")
    else:
        print(f"\n在 '{target_directory}' 中未找到最近3天内修改过的文件夹。")


# 高级版本：持续监控模式
def monitor_folders(directory, check_interval=60):
    """
    持续监控目录，实时显示新修改的文件夹[5](@ref)

    参数:
    directory: 要监控的目录
    check_interval: 检查间隔（秒）
    """
    print(f"开始监控目录: {directory}")
    print("按 Ctrl+C 停止监控\n")

    # 记录已知的文件夹修改时间
    folder_mtimes = {}

    try:
        while True:
            current_folders = []

            # 收集所有文件夹及其修改时间
            for root, dirs, files in os.walk(directory):
                for dir_name in dirs:
                    folder_path = os.path.join(root, dir_name)
                    current_folders.append(folder_path)

                    try:
                        current_mtime = os.path.getmtime(folder_path)

                        # 如果是新文件夹或者修改时间有变化
                        if (folder_path not in folder_mtimes or
                                current_mtime != folder_mtimes[folder_path]):

                            if folder_path in folder_mtimes:
                                print(f"检测到文件夹更新: {folder_path}")
                            else:
                                print(f"发现新文件夹: {folder_path}")

                            mod_time = get_folder_modification_time(folder_path)
                            print(f"修改时间: {mod_time}\n")

                            folder_mtimes[folder_path] = current_mtime

                    except Exception:
                        continue

            # 移除已不存在的文件夹
            for folder in list(folder_mtimes.keys()):
                if folder not in current_folders:
                    print(f"文件夹已被删除: {folder}")
                    del folder_mtimes[folder]

            time.sleep(check_interval)

    except KeyboardInterrupt:
        print("\n监控已停止")


if __name__ == "__main__":
    print("=== 查找三天内更新过的文件夹 ===\n")

    # 运行主程序
    main()

    # 询问是否启动监控模式
    response = input("\n是否启动持续监控模式？(y/n): ").strip().lower()
    if response == 'y':
        target_dir = input("请输入要监控的目录路径: ").strip()
        if not target_dir:
            target_dir = os.getcwd()

        if os.path.exists(target_dir):
            monitor_folders(target_dir)
        else:
            print("目录不存在！")